package com.water.wfo.component.spring.util;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * spring获取bena
 *
 * @author 崔亚东
 * @time 2021-01-05 10:32:03
 */
@Component
public class SpringBeanUtil implements ApplicationContextAware {

    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext){
        setContext(applicationContext);
    }

    /**
     * 设置上下文对象
     * @return context
     */
    private static void setContext(ApplicationContext applicationContext) {
        context = applicationContext;
    }

    /**
     * 获取上下文对象
     *
     * @return context
     */
    public static ApplicationContext getContext() {
        return context;
    }

    /**
     * 判断上下文对象是否为空
     * @return
     */
    public static boolean checkApplicationContext() {
        return getContext() != null;
    }

    /**
     * 根据name获取bean
     * @param name
     * @param <T>
     * @return
     */
    public static <T> T getBean(String name) {
        if (checkApplicationContext()) {
            return (T) getContext().getBean(name);
        } else {
            return null;
        }
    }

    /**
     * 根据class 获取bean
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> clazz) {
        if (checkApplicationContext()) {
            return getContext().getBean(clazz);
        } else {
            return null;
        }
    }

}
